package net.adetech.cjg.innerservice.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.adetech.cjg.innerservice.entity.Bzhzrw;
import net.adetech.cjg.innerservice.entity.Qzb;
import net.adetech.cjg.innerservice.entity.Sqjl;
import net.adetech.cjg.innerservice.entity.Yxzl;
import net.adetech.cjg.innerservice.mapper.*;
import net.adetech.cjg.innerservice.utils.SixInOneUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class SqjlController {

    @Autowired
    SqjlDao sqjlDao;

    @Autowired
    YxzlDao yxzlDao;

    @Autowired
    SixInOneUtils sixInOneUtils;

    @Autowired
    QzbDao qzbDao;

    @Autowired
    BzhzrwDao bzhzrwDao;

    @Autowired
    private HttpServletRequest request;

    private static long maxPicSize = 3000000;

    private String getClientIp() {
        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        return remoteAddr;
    }

    private String getClientId() {
        return MessageController.getClientId(getClientIp());
    }


    @RequestMapping(value = "/cjg/bcsqjl", produces = "application/json")
    public String bcsqjl(String msg) {
        String clientId = getClientId();

        JSONObject msgJson = JSONObject.parseObject(msg);

        JSONObject table1Json = msgJson.getJSONObject("form").getJSONObject("table1");
        JSONObject table2Json = msgJson.getJSONObject("form").getJSONObject("table2");
        JSONObject currentInfo = msgJson.getJSONObject("form").getJSONObject("currentInfo");

        JSONObject sqrJson = sqrJsonMap.get(clientId);
        JSONObject dlrJson = dlrJsonMap.get(clientId);
        String signSrc = signSrcMap.get(clientId);
        String signSrc2 = signSrcMap2.get(clientId);
        String serviceType = serviceTypeMap.get(clientId);


        String sfzmhm = null;
        String xm = null;

        if (sqrJson != null) {
            JSONObject sfzJson = JSONObject.parseObject(sqrJson.toJSONString());
            sfzJson.put("type", "sfz");
            msgJson.getJSONObject("form").put("sfz", sfzJson);

            sfzmhm = sqrJson.getString("sfzmhm");
            xm = sqrJson.getString("xm");
        } else {

            sfzmhm = table1Json.getString("sfzmhm1");
            if (sfzmhm == null || "".equals(sfzmhm)) {
                sfzmhm = table2Json.getString("sfzmhm");
            }


            xm = table1Json.getString("xm");
            if (xm == null || "".equals(xm)) {
                xm = table2Json.getString("xm");
            }

        }


        msgJson.getJSONObject("form").put("signSrc", signSrc);
        msgJson.getJSONObject("form").put("signSrc2", signSrc2);
        msgJson.getJSONObject("form").put("sqr", sqrJson);
        msgJson.getJSONObject("form").put("dlr", dlrJson);
        msgJson.getJSONObject("form").put("serviceType", serviceType);


        String userType = currentInfo.getString("type");
        JSONObject personJson = msgJson.getJSONObject("person");
        String scry = msgJson.getJSONObject("form").getString("scry");
        String scrymc = msgJson.getJSONObject("form").getString("scrymc");
        String orgCode = msgJson.getJSONObject("form").getString("orgCode");
        String yhzh = msgJson.getJSONObject("form").getString("userName");

        Qzb qzb = qzbDao.getQmbByYhzh(yhzh);
        if (qzb != null) {
            msgJson.getJSONObject("form").put("mySign", qzb.getQzImg());
        }


        Sqjl sqjl = new Sqjl();
        sqjl.setYmJson(msgJson.toJSONString());
        sqjl.setScry(scry);
        sqjl.setScrymc(scrymc);
        sqjl.setOrgCode(orgCode);
        sqjl.setWczt("0");
        sqjl.setBljd("0");
        sqjl.setDybz("0");



        sqjl.setXm(xm);
        sqjl.setSfzh(sfzmhm);

        String lsh = "";


        if ("man".equals(userType) || "newMan".equals(userType)) {
            if (table1Json != null) {
                lsh = table1Json.getString("lsh");
                sqjl.setYwlx(table1Json.getString("ywlx1"));
                sqjl.setYwlxmc(table1Json.getString("ywlxmc1"));
                sqjl.setSjhm(table1Json.getString("sjhm"));
                sqjl.setLsh(table1Json.getString("lsh"));
                sqjl.setDhhm(table1Json.getString("gddh"));
                sqjl.setYjdz(table1Json.getString("yjdz"));
                sqjl.setYjdh(table1Json.getString("sjhm"));
                sqjl.setYwfl("2");
            }
        } else if ("car".equals(userType) || "newCar".equals(userType) || "transferIn".equals(userType)) {
            if (table2Json != null) {
                lsh = table2Json.getString("lsh");
                sqjl.setYwlx(table2Json.getString("ywlx1"));
                sqjl.setYwlxmc(table2Json.getString("ywlxmc1"));
                sqjl.setSjhm(table2Json.getString("sjhm"));
                sqjl.setLsh(table2Json.getString("lsh"));
                sqjl.setDhhm(table2Json.getString("sjhm"));
                sqjl.setYjdz(table2Json.getString("yjdz"));
                sqjl.setYjdh(table2Json.getString("sjhm"));
                sqjl.setHphm(table2Json.getString("hphm"));
                sqjl.setYwfl("1");
            }
        }

        JSONArray imageDataArray = msgJson.getJSONObject("form").getJSONArray("imageData");
        saveImageData(lsh, imageDataArray);

        if (personJson != null) {
            sqjl.setHjdz(personJson.getString("address"));
        }


        JSONObject result = new JSONObject();
        result.put("result", "ok");
        try {
            long id = sqjlDao.getCommonId();
            sqjl.setId(id);
            sqjlDao.saveSqjl(sqjl);
            sqjl.setId(id);
            sqjlDao.saveSqjlJson(sqjl);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "error");
        }
        if(result.getString("result").equals("ok"))
        {
            clearClientInfo(clientId);

        }

        return result.toJSONString();
    }


    /**
     * 补证换证接口
     *
     * @param msg
     * @return
     */


    @RequestMapping(value = "/cjg/bzhz", produces = "application/json")
    public String bzhz(String msg) {
        JSONObject resultJson = new JSONObject();
        String clientId = getClientId();
        JSONObject msgJson = JSONObject.parseObject(msg);
        JSONObject formJson = msgJson.getJSONObject("form");
//        String sfztp = msgJson.getString("sfztp");
//        sfztp = sfztp.substring("data:image/png;base64,".length());
//        sfztp = compressUnderSize(sfztp,maxPicSize);
        String sfzmzp = this.getSfzmzp(clientId,msgJson);
        String sqrxczp = this.getSqrxczp(clientId);

        String ywlx = formJson.getString("ywlx");
        String ywyy = formJson.getString("ywyy");

        String yhdh = formJson.getString("userName");
        String ip = "10.231.49.12";
        String lxzsxxdz = formJson.getJSONObject("table1").getString("yjdz");
        String lxzsxzqh = formJson.getJSONObject("table1").getString("lxzsxzqh");
        String djzsxzqh = formJson.getJSONObject("table1").getString("djzsxzqh");
        String djzsxxdz = formJson.getJSONObject("table1").getString("djzsxxdz");
        String lxzsyzbm = formJson.getJSONObject("table1").getString("yzbm");
        String lxdh = formJson.getJSONObject("table1").getString("gddh");
        String sjhm = formJson.getJSONObject("table1").getString("sjhm");
        String dzyx = formJson.getJSONObject("table1").getString("dzyx");
        String sfzmhm = formJson.getJSONObject("table1").getString("sfzmhm1");
        String orgCode = msgJson.getJSONObject("form").getString("orgCode");
        boolean bgbz = formJson.getBoolean("bgbz");

        JSONObject sqrJson = sqrJsonMap.get(clientId);
        JSONObject dlrJson = dlrJsonMap.get(clientId);
        String signSrc = signSrcMap.get(clientId);
        String signSrc2 = signSrcMap2.get(clientId);


        if ("C".equals(ywlx) && "A".equals(ywyy)) {
            JSONObject paramJson0290 = new JSONObject();
            paramJson0290.put("sfzmhm", sfzmhm);
            JSONObject resultJson0290 = sixInOneUtils.call(paramJson0290, "02C90");

            if (!("1".equals(resultJson0290.getString("code")) && "1".equals(resultJson0290.getString("sl")))) {
                resultJson.put("result", "need_health");
                resultJson.put("msg", "该申请人不存在最近六个月体检数据,无法办理!");
                return resultJson.toJSONString();
            }
        }


        //修改联系方式
        {
            JSONObject paramJson = new JSONObject();
            paramJson.put("lxzs", lxzsxxdz);
            paramJson.put("sjhm", sjhm);
            paramJson.put("lxdh", lxdh);
            paramJson.put("dzyx", dzyx);
            paramJson.put("yzbm", lxzsyzbm);
            paramJson.put("sfzmhm", sfzmhm);
            sixInOneUtils.call(paramJson, "02C65");
        }



        String lsh = "";


        if (sfzmzp!=null&&sfzmzp.length()>0)
        {
            JSONObject requestJson2502 = new JSONObject();
            requestJson2502.put("xtlb","02");
            requestJson2502.put("ywzj",sfzmhm);
            requestJson2502.put("ywzldm","20003");
            requestJson2502.put("yxhzl",sfzmzp);
            JSONObject resultJson2502= sixInOneUtils.call(requestJson2502, "25C02");
            System.out.println(resultJson2502.toJSONString());
        }

        if (sqrxczp!=null&&sqrxczp.length()>0)
        {
            JSONObject requestJson2502 = new JSONObject();
            requestJson2502.put("xtlb","02");
            requestJson2502.put("ywzj",sfzmhm);
            requestJson2502.put("ywzldm","20201");
            requestJson2502.put("yxhzl",sqrxczp);
            JSONObject resultJson2502= sixInOneUtils.call(requestJson2502, "25C02");
            System.out.println(resultJson2502.toJSONString());
        }


        if(!bgbz){
            //调用接口02C89 开始
            JSONObject requestJson0289 = new JSONObject();
            requestJson0289.put("sfzmhm", sfzmhm);
            requestJson0289.put("ywlx", ywlx);
            requestJson0289.put("ywyy", ywyy);
            requestJson0289.put("yhdh", yhdh);
            requestJson0289.put("ip", ip);
            requestJson0289.put("lxzsxxdz", lxzsxxdz);
            requestJson0289.put("lxzsxzqh", lxzsxzqh);
            requestJson0289.put("lxzsyzbm", lxzsyzbm);
            requestJson0289.put("lxdh", lxdh);
            requestJson0289.put("sjhm", sjhm);
            requestJson0289.put("dzyx", dzyx);


//            String zp = sqrJson.getString("zp");
//            zp = compressUnderSize(zp,maxPicSize);
//            try {
//                sfztp = URLEncoder.encode(sfztp,"utf-8");
//                zp = URLEncoder.encode(zp,"utf-8");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }






            //requestJson0289.put("sfzmzp", sfzmzp);
            //requestJson0289.put("sqrxczp", sqrxczp);




            JSONObject resultJson0289 = sixInOneUtils.call(requestJson0289, "02C89");

            String retcode0289 = resultJson0289.getString("retcode");
            String retdesc0289 = resultJson0289.getString("retdesc");



            if (retcode0289 != null && "1".equals(retcode0289)) {
                lsh = resultJson0289.getString("retval");
            } else {
                String message0289 = resultJson0289.getString("message");
                resultJson.put("result", "error");
                if (message0289 != null && !message0289.equals("")) {
                    resultJson.put("msg", message0289);
                } else if (retdesc0289 != null && !retdesc0289.equals("")) {
                    resultJson.put("msg", retdesc0289);
                } else {
                    resultJson.put("msg", "保存失败!");
                }
                return resultJson.toJSONString();
            }


            //调用接口02C89 结束
        }

        else {

            String sfzyxq = sqrJson.getString("zjyxq");
            String sfzyxqs = "";
            String sfzyxqz = "";
            if (sfzyxq!=null)
            {
                sfzyxqs = sfzyxq.split("-")[0].replaceAll("\\.","-").trim();
                sfzyxqz = sfzyxq.split("-")[1].replaceAll("\\.","-").trim();

            }
            String xm = sqrJson.getString("xm");

            Bzhzrw bzhzrw = new Bzhzrw();
            String bzhzrwId = UUID.randomUUID().toString();
            bzhzrw.setId(bzhzrwId);
            bzhzrw.setSfzmhm(sfzmhm);
            bzhzrw.setDjzsxxdz(djzsxxdz);
            bzhzrw.setDjzsxzqh(djzsxzqh);
            bzhzrw.setLxzsxxdz(lxzsxxdz);
            bzhzrw.setLxzsxzqh(lxzsxzqh);
            bzhzrw.setSjhm(sjhm);
            bzhzrw.setOrgCode(orgCode);
            bzhzrw.setSfzyxqs(sfzyxqs);
            bzhzrw.setSfzyxqz(sfzyxqz);
            bzhzrw.setXm(xm);
            bzhzrw.setYwyy(ywyy);
            bzhzrw.setClientId(Long.parseLong(clientId));

            this.bzhzrwDao.saveBzhzrw(bzhzrw);

            for (int i = 0; i < 120; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bzhzrw = this.bzhzrwDao.getBzhzrwById(bzhzrwId);
                if (!bzhzrw.getRwzt().equals("0")) {
                    break;
                }
            }

            if (bzhzrw.getRwzt().equals("1")) {
                lsh = bzhzrw.getBz();
//                JSONObject param0221 = new JSONObject();
//                param0221.put("sfzmhm", sfzmhm);
//                JSONObject result0221 = sixInOneUtils.call(param0221, "02C21");
//                lsh = result0221.getString("lsh");
                if (lsh == null) {
                    resultJson.put("result", "error");
                    resultJson.put("msg", "请求失败，请尝试其他方式保存。");
                }

            } else if (bzhzrw.getRwzt().equals("0")) {
                resultJson.put("result", "error");
                resultJson.put("msg", "服务助手请求超时，请检查服务助手状态。");
                bzhzrw.setRwzt("-1");
                bzhzrw.setBz("服务助手请求超时，请检查服务助手状态");
                this.bzhzrwDao.updateBzhzrwzt(bzhzrw);
                return resultJson.toJSONString();
            } else {
                resultJson.put("result", "error");
                resultJson.put("msg", bzhzrw.getBz());
                return resultJson.toJSONString();
            }
        }



        JSONObject table1Json = msgJson.getJSONObject("form").getJSONObject("table1");


        JSONObject sfzJson = null;
        if (sqrJson != null) {
            sfzJson = JSONObject.parseObject(sqrJson.toJSONString());
            sfzJson.put("type", "sfz");
        }

        msgJson.getJSONObject("form").put("signSrc", signSrc);
        msgJson.getJSONObject("form").put("signSrc2", signSrc2);
        msgJson.getJSONObject("form").put("sfz", sfzJson);
        msgJson.getJSONObject("form").put("sqr", sqrJson);
        msgJson.getJSONObject("form").put("dlr", dlrJson);


        JSONObject personJson = msgJson.getJSONObject("person");
        String scry = msgJson.getJSONObject("form").getString("scry");
        String scrymc = msgJson.getJSONObject("form").getString("scrymc");
        String yhzh = msgJson.getJSONObject("form").getString("userName");


        Qzb qzb = qzbDao.getQmbByYhzh(yhzh);
        if (qzb != null) {
            msgJson.getJSONObject("form").put("mySign", qzb.getQzImg());
        }

        Sqjl sqjl = new Sqjl();
        sqjl.setYmJson(msgJson.toJSONString());
        sqjl.setScry(scry);
        sqjl.setScrymc(scrymc);
        sqjl.setOrgCode(orgCode);
        sqjl.setWczt("0");
        sqjl.setBljd("0");
        sqjl.setDybz("0");
        sqjl.setYwfl("2");



        if (table1Json != null) {
            sqjl.setYwlx(table1Json.getString("ywlx1"));
            sqjl.setYwlxmc(table1Json.getString("ywlxmc1"));
            sqjl.setSjhm(table1Json.getString("sjhm"));
            sqjl.setLsh(lsh);
            sqjl.setDhhm(table1Json.getString("gddh"));
            sqjl.setYjdz(table1Json.getString("yjdz"));
            sqjl.setYjdh(table1Json.getString("sjhm"));
            sqjl.setXm(table1Json.getString("xm"));
            sqjl.setSfzh(table1Json.getString("sfzmhm1"));
        }


        JSONArray imageDataArray = msgJson.getJSONObject("form").getJSONArray("imageData");
        saveImageData(lsh, imageDataArray);

        if (personJson != null) {
            sqjl.setHjdz(personJson.getString("address"));
        }


        resultJson.put("result", "ok");
        resultJson.put("lsh", lsh);
        try {
            long id = sqjlDao.getCommonId();
            sqjl.setId(id);
            sqjlDao.saveSqjl(sqjl);
            sqjl.setId(id);
            sqjlDao.saveSqjlJson(sqjl);
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.put("result", "error");
            resultJson.put("msg", e.getMessage());
        }
        if(resultJson.getString("result").equals("ok"))
        {
            clearClientInfo(clientId);

        }
        return resultJson.toJSONString();
    }


    @RequestMapping(value = "/cjg/lnmj", produces = "application/json")
    public String lnmj(String msg)
    {
        JSONObject resultJson = new JSONObject();



        String clientId = getClientId();

        JSONObject sqrJson = sqrJsonMap.get(clientId);
        JSONObject dlrJson = dlrJsonMap.get(clientId);
        String signSrc = signSrcMap.get(clientId);
        String signSrc2 = signSrcMap2.get(clientId);

        JSONObject msgJson = JSONObject.parseObject(msg);
        JSONObject formJson = msgJson.getJSONObject("form");
        JSONObject tableJson = formJson.getJSONObject("table2");

        String jbr = formJson.getString("scrymc");
        String xh = tableJson.getString("xh");
        String hphm = tableJson.getString("hphm");
        String hpzl = tableJson.getString("hpzl");
        String sxrq = tableJson.getString("bxsxrq");
        String zzrq = tableJson.getString("bxzzrq");
        String fzjg = tableJson.getString("fzjg");
        String orgCode = formJson.getString("orgCode");
        String glbm = departDao.getGlbm(orgCode);

        String sfzmzp = this.getSfzmzp(clientId,msgJson);
        String sqrxczp = this.getSqrxczp(clientId);


        JSONObject requestJson = new JSONObject();
        requestJson.put("sxrq", sxrq);
        requestJson.put("zzrq", zzrq);
        requestJson.put("fzjg", fzjg);
        requestJson.put("xh", xh);
        requestJson.put("hphm", hphm.substring(1));
        requestJson.put("hpzl", hpzl);
        requestJson.put("jbr", jbr);
        requestJson.put("glbm", glbm);
        System.out.println(glbm);
        requestJson.put("sfzmzp", sfzmzp);
        requestJson.put("sqrxczp", sqrxczp);



        JSONObject responseJson = sixInOneUtils.call(requestJson, "01CQ9");
        String lsh = responseJson.getString("lsh");
        if (lsh != null && lsh.length() == 13) {

        } else {
            String message = responseJson.getString("message");
            resultJson.put("result", "error");
            resultJson.put("msg", message);
            return resultJson.toJSONString();
        }



        JSONObject sfzJson = null;
        if (sqrJson != null) {
            sfzJson = JSONObject.parseObject(sqrJson.toJSONString());
            sfzJson.put("type", "sfz");
        }


        msgJson.getJSONObject("form").put("signSrc", signSrc);
        msgJson.getJSONObject("form").put("signSrc2", signSrc2);
        msgJson.getJSONObject("form").put("sfz", sfzJson);
        msgJson.getJSONObject("form").put("sqr", sqrJson);
        msgJson.getJSONObject("form").put("dlr", dlrJson);


        JSONObject personJson = msgJson.getJSONObject("person");
        String scry = msgJson.getJSONObject("form").getString("scry");
        String scrymc = msgJson.getJSONObject("form").getString("scrymc");

        Sqjl sqjl = new Sqjl();
        sqjl.setYmJson(msgJson.toJSONString());
        sqjl.setScry(scry);
        sqjl.setScrymc(scrymc);
        sqjl.setOrgCode(orgCode);
        sqjl.setHphm(hphm);
        sqjl.setWczt("0");
        sqjl.setBljd("0");
        sqjl.setDybz("0");
        sqjl.setYwfl("1");


        if (tableJson != null) {
            sqjl.setYwlx(tableJson.getString("ywlx1"));
            sqjl.setYwlxmc(tableJson.getString("ywlxmc1"));
            sqjl.setSjhm(tableJson.getString("sjhm"));
            sqjl.setLsh(lsh);
            sqjl.setDhhm(tableJson.getString("gddh"));
            sqjl.setYjdz(tableJson.getString("yjdz"));
            sqjl.setYjdh(tableJson.getString("sjhm"));

            sqjl.setXm(tableJson.getString("xm"));
            sqjl.setSfzh(tableJson.getString("sfzmhm"));
        }


        JSONArray imageDataArray = msgJson.getJSONObject("form").getJSONArray("imageData");
        saveImageData(lsh, imageDataArray);

        if (personJson != null) {
            sqjl.setHjdz(personJson.getString("address"));
        }


        resultJson.put("result", "ok");
        resultJson.put("lsh", lsh);
        try {
            long id = sqjlDao.getCommonId();
            sqjl.setId(id);
            sqjlDao.saveSqjl(sqjl);
            sqjl.setId(id);
            sqjlDao.saveSqjlJson(sqjl);
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.put("result", "error");
            resultJson.put("msg", e.getMessage());
        }
        if(resultJson.getString("result").equals("ok"))
        {
            clearClientInfo(clientId);

        }
        return resultJson.toJSONString();

    }


    /**
     * 补换领号牌行驶证
     *
     * @param msg
     * @return
     */
    @RequestMapping(value = "/cjg/bhlhpxsz", produces = "application/json")
    public String bhlhpxsz(String msg) {
        JSONObject resultJson = new JSONObject();



        String clientId = getClientId();

        JSONObject sqrJson = sqrJsonMap.get(clientId);
        JSONObject dlrJson = dlrJsonMap.get(clientId);
        String signSrc = signSrcMap.get(clientId);
        String signSrc2 = signSrcMap2.get(clientId);

        JSONObject msgJson = JSONObject.parseObject(msg);
        JSONObject formJson = msgJson.getJSONObject("form");
        JSONObject tableJson = formJson.getJSONObject("table2");
        String ywlx = formJson.getString("ywlx");
        String ywyy = formJson.getString("ywyy");
        String sqyy = formJson.getString("sqyy");
        String xh = tableJson.getString("xh");
        String hphm = tableJson.getString("hphm");
        String hpzl = tableJson.getString("hpzl");
        String jbr = formJson.getString("scrymc");
        String orgCode = formJson.getString("orgCode");
        String clsbdh = tableJson.getString("clsbdh");





        String glbm = departDao.getGlbm(orgCode);




        JSONObject requestJson = new JSONObject();
        requestJson.put("ywlx", ywlx);
        requestJson.put("ywyy", ywyy);
        requestJson.put("sqyy", sqyy);
        requestJson.put("xh", xh);
        requestJson.put("hphm", hphm);
        requestJson.put("hpzl", hpzl);
        requestJson.put("jbr", jbr);
        requestJson.put("glbm", glbm);



//        String sfzmzp = msgJson.getString("sfztp");
//        sfzmzp = sfzmzp.substring("data:image/png;base64,".length());
//        sfzmzp = compressUnderSize(sfzmzp,maxPicSize);
//        String sqrxczp = sqrJson.getString("zp");
//        sqrxczp = compressUnderSize(sqrxczp,maxPicSize);



        String sfzmzp = this.getSfzmzp(clientId,msgJson);
        String sqrxczp = this.getSqrxczp(clientId);

        //requestJson.put("sfzmzp", sfzmzp);
        //requestJson.put("sqrxczp", sqrxczp);


        if (sfzmzp!=null&&sfzmzp.length()>0)
        {
            JSONObject requestJson2502 = new JSONObject();
            requestJson2502.put("xtlb","01");
            requestJson2502.put("ywzj",clsbdh);
            requestJson2502.put("ywzldm","10202");
            requestJson2502.put("yxhzl",sfzmzp);
            JSONObject resultJson2502= sixInOneUtils.call(requestJson2502, "25C02");
            System.out.println(resultJson2502.toJSONString());
        }

        if (sqrxczp!=null&&sqrxczp.length()>0)
        {
            JSONObject requestJson2502 = new JSONObject();
            requestJson2502.put("xtlb","01");
            requestJson2502.put("ywzj",clsbdh);
            requestJson2502.put("ywzldm","10268");
            requestJson2502.put("yxhzl",sqrxczp);
            JSONObject resultJson2502= sixInOneUtils.call(requestJson2502, "25C02");
            System.out.println(resultJson2502.toJSONString());
        }


        JSONObject responseJson = sixInOneUtils.call(requestJson, "01C69");
        String lsh = responseJson.getString("lsh");
        if (lsh != null && lsh.length() == 13) {

        } else {
            String message = responseJson.getString("message");
            resultJson.put("result", "error");
            resultJson.put("msg", message);
            return resultJson.toJSONString();
        }



        JSONObject sfzJson = null;
        if (sqrJson != null) {
            sfzJson = JSONObject.parseObject(sqrJson.toJSONString());
            sfzJson.put("type", "sfz");
        }


        msgJson.getJSONObject("form").put("signSrc", signSrc);
        msgJson.getJSONObject("form").put("signSrc2", signSrc2);
        msgJson.getJSONObject("form").put("sfz", sfzJson);
        msgJson.getJSONObject("form").put("sqr", sqrJson);
        msgJson.getJSONObject("form").put("dlr", dlrJson);


        JSONObject personJson = msgJson.getJSONObject("person");
        String scry = msgJson.getJSONObject("form").getString("scry");
        String scrymc = msgJson.getJSONObject("form").getString("scrymc");

        Sqjl sqjl = new Sqjl();
        sqjl.setYmJson(msgJson.toJSONString());
        sqjl.setScry(scry);
        sqjl.setScrymc(scrymc);
        sqjl.setOrgCode(orgCode);
        sqjl.setHphm(hphm);
        sqjl.setWczt("0");
        sqjl.setBljd("0");
        sqjl.setDybz("0");
        sqjl.setYwfl("1");


        if (tableJson != null) {
            sqjl.setYwlx(tableJson.getString("ywlx1"));
            sqjl.setYwlxmc(tableJson.getString("ywlxmc1"));
            sqjl.setSjhm(tableJson.getString("sjhm"));
            sqjl.setLsh(lsh);
            sqjl.setDhhm(tableJson.getString("gddh"));
            sqjl.setYjdz(tableJson.getString("yjdz"));
            sqjl.setYjdh(tableJson.getString("sjhm"));

            sqjl.setXm(tableJson.getString("xm"));
            sqjl.setSfzh(tableJson.getString("sfzmhm"));
        }


        JSONArray imageDataArray = msgJson.getJSONObject("form").getJSONArray("imageData");
        saveImageData(lsh, imageDataArray);

        if (personJson != null) {
            sqjl.setHjdz(personJson.getString("address"));
        }


        resultJson.put("result", "ok");
        resultJson.put("lsh", lsh);
        try {
            long id = sqjlDao.getCommonId();
            sqjl.setId(id);
            sqjlDao.saveSqjl(sqjl);
            sqjl.setId(id);

            sqjlDao.saveSqjlJson(sqjl);
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.put("result", "error");
            resultJson.put("msg", e.getMessage());
        }
        if(resultJson.getString("result").equals("ok"))
        {
            clearClientInfo(clientId);

        }
        return resultJson.toJSONString();
    }


    /**
     * 修改驾驶证联系方式
     *
     * @param yjdz    邮寄地址
     * @param sjhm    手机号码
     * @param gddh    联系电话
     * @param yzbm    邮政编码
     * @param dzyx    电子邮箱
     * @param sfzmhm1 身份证明号码
     * @return
     */
    @RequestMapping(value = "/cjg/xgjszlxfs", produces = "application/json")
    public String xgjszlxfs(String yjdz, String sjhm, String gddh, String yzbm, String dzyx, String sfzmhm1) {
        JSONObject paramJson = new JSONObject();
        paramJson.put("lxzs", yjdz);
        paramJson.put("sjhm", sjhm);
        paramJson.put("lxdh", gddh);
        paramJson.put("yzbm", yzbm);
        paramJson.put("dzyx", dzyx);
        paramJson.put("sfzmhm", sfzmhm1);
        JSONObject resultJson = sixInOneUtils.call(paramJson, "02C65");
        return resultJson.toJSONString();
    }


    /**
     * 修改机动车联系方式
     *
     * @param hpzl 号牌种类
     * @param hphm 号牌号码
     * @param yzbm 邮政编码
     * @param gddh 联系电话
     * @param sjhm 手机号码
     * @return
     */
    @RequestMapping(value = "/cjg/xgjdclxfs", produces = "application/json")
    public String xgjdclxfs(String hpzl, String hphm, String yzbm, String gddh, String sjhm) {
        hphm = hphm.substring(1);
        JSONObject paramJson = new JSONObject();
        paramJson.put("hpzl", hpzl);
        paramJson.put("hphm", hphm);

        paramJson.put("sjhm", sjhm);
        paramJson.put("yzbm1", yzbm);
//        paramJson.put("dzyx",dzyx);
        paramJson.put("lxdh", gddh);
        JSONObject resultJson = sixInOneUtils.call(paramJson, "01C73");
        return resultJson.toJSONString();
    }


    private void saveImageData(String lsh, JSONArray imageDataArray) {
        for (int i = 0; i < imageDataArray.size(); i++) {
            String uuid = imageDataArray.getJSONObject(i).getString("uuid");
            Yxzl yxzl = new Yxzl();
            yxzl.setLsh(lsh);
            yxzl.setUuid(uuid);
            yxzl.setSxh(i + 1);
            yxzlDao.confirmAddYxzl(yxzl);
        }
    }


    private static Map<String, String> serviceTypeMap = new HashMap<>();
    private static Map<String, JSONObject> sqrJsonMap = new HashMap<>();
    private static Map<String, JSONObject> dlrJsonMap = new HashMap<>();
    private static Map<String, String> signSrcMap = new HashMap<>();
    private static Map<String, String> signSrcMap2 = new HashMap<>();
    private static Map<String,String> sqrsfzzpMap = new HashMap<>();
    private static Map<String,String> xcrxMap = new HashMap<>();


    private static Object lock = new Object();


    public static void addServiceType(String clientId, String serviceType) {
        serviceTypeMap.put(clientId, serviceType);
    }

    public static void addPerson1(String clientId, JSONObject person1) {
        String serviceType = serviceTypeMap.get(clientId);
        if ("1".equals(serviceType) || "5".equals(serviceType) || "3".equals(serviceType)) {
            sqrJsonMap.put(clientId, person1);
        } else if ("2".equals(serviceType)) {
//        } else if ("2".equals(serviceType)) {
            dlrJsonMap.put(clientId, person1);
        }

    }

    public static void addPerson2(String clientId, JSONObject person2) {


        String serviceType = serviceTypeMap.get(clientId);
        if ("5".equals(serviceType)) {
            dlrJsonMap.put(clientId, person2);
        } else if ("2".equals(serviceType)) {
            sqrJsonMap.put(clientId, person2);
        }


    }

    public static void addSignSrc(String clientId, String signSrc) {
        signSrcMap.put(clientId, signSrc);
    }

    public static void addSignSrc2(String clientId, String signSrc) {
        signSrcMap2.put(clientId, signSrc);
    }


    public static void clearClientInfo(String clientId) {
        synchronized (lock) {
            serviceTypeMap.remove(clientId);
            sqrJsonMap.remove(clientId);
            dlrJsonMap.remove(clientId);
            signSrcMap.remove(clientId);
            signSrcMap.remove(clientId);

            sqrsfzzpMap.remove(clientId);
            xcrxMap.remove(clientId);
        }
    }


    /**
     * 将图片压缩到指定大小以内
     *
     * @param srcImgData 源图片数据
     * @param maxSize    目的图片大小
     * @return 压缩后的图片数据
     */
    public static byte[] compressUnderSize(byte[] srcImgData, long maxSize) {
        double scale = 0.9;
        byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length);

        if (imgData.length > maxSize) {
            do {
                try {
                    imgData = compress(imgData, scale);

                } catch (IOException e) {
                    throw new IllegalStateException("压缩图片过程中出错，请及时联系管理员！", e);
                }

            } while (imgData.length > maxSize);
        }

        return imgData;
    }


    public static byte[] compress(byte[] srcImgData, double scale) throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        int width = (int) (bi.getWidth() * scale); // 源图宽度
        int height = (int) (bi.getHeight() * scale); // 源图高度

        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null); // 绘制处理后的图
        g.dispose();

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bOut);
        return bOut.toByteArray();
    }


    public String compressUnderSize(String srcImg, long maxSize) {
        byte[] srcImgData = new byte[0];
        try {
            srcImgData = new BASE64Decoder().decodeBuffer(srcImg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        double scale = 0.9;
        byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length);

        if (imgData.length > maxSize) {
            do {
                try {
                    imgData = compress(imgData, scale);

                } catch (IOException e) {
                    throw new IllegalStateException("压缩图片过程中出错，请及时联系管理员！", e);
                }

            } while (imgData.length > maxSize);
        }
        return new BASE64Encoder().encode(imgData);
    }






    @RequestMapping(value = "/cjg/scan", produces = "application/json")
    public String springUpload(String scry, String base64, String type, String uuid,String sfzmhm) {
        JSONObject result = new JSONObject();

        try {

            if ("4001".equals(type)||"1001".equals(type))
            {
                synchronized (lock){
                    String clinetId = getClientId();
                    if ("4001".equals(type))
                    {
                        sqrsfzzpMap.put(clinetId,base64);
                    }
                    if ("1001".equals(type))
                    {
                        xcrxMap.put(clinetId,base64);
                    }
                }
            }

            Yxzl yxzl = new Yxzl();
            yxzl.setScry(scry);
            yxzl.setTp(base64);
            yxzl.setZllb(type);
            yxzl.setUuid(uuid);
            yxzl.setSfzmhm(sfzmhm);
            yxzlDao.addNewYxzl(yxzl);
            result.put("result", "ok");
        } catch (Exception e) {
            result.put("result", "error");
        }
        return result.toJSONString();

    }


    @RequestMapping(value = "/cjg/upload", produces = "application/json")
    public String upload(@RequestBody String input) {

        return input;

    }


    private String getSqrxczp(String clientId)
    {
        String sqrxczp = xcrxMap.get(clientId);
        try {
            if (sqrxczp!=null)
            {
                sqrxczp = URLEncoder.encode(sqrxczp,"utf-8");
            }
        }
        catch (Exception e)
        {

        }
        return sqrxczp;
    }

    private String getSfzmzp(String clientId,JSONObject msgJson)
    {
        String sfzmzp = sqrsfzzpMap.get(clientId);
        try {
            if (sfzmzp!=null)
            {
                sfzmzp = URLEncoder.encode(sfzmzp,"utf-8");

            }
            else {
                sfzmzp = msgJson.getString("sfztp");
                sfzmzp = sfzmzp.substring("data:image/png;base64,".length());
                sfzmzp = compressUnderSize(sfzmzp,maxPicSize);
                Base64ToImage(sfzmzp,"/Users/zhangsong/Downloads/sfz.png");
                sfzmzp = URLEncoder.encode(sfzmzp,"utf-8");

            }
        }
        catch (Exception e)
        {

        }
        return sfzmzp;
    }


    public static boolean Base64ToImage(String base64,String filePath) { // 对字节数组字符串进行Base64解码并生成图片

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Autowired
    private DepartDao departDao;


    @Value("${app.domain}")
    private String appDomain;
}

